package core.transfer;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * Class LocalTranfer : Enables to copy a file in a local context
 * @project Universalcopy
 * @author Aurele TONNERRE, Romain Monnier
 */
public class LocalTransfer extends ProtocolTransfer
{
    /**
     * Constructs a LocalTranfer with path of the file and the target directory in local machine
     * @param urlOrigin : the fukkpath of the file to copy
     * @param urlDestination : the fullpath of the target directory
     * @param theFile  : informations about the file to copy
     */
    public LocalTransfer(String urlOrigin, String urlDestination, core.File theFile) {
        super(urlOrigin, urlDestination);
        file = theFile.getFile();
    }
    
    
    /**
     * Enables to download a file from local
     */
    public void download() {
        //file = new core.File(urlOrigin);
        System.out.println("Récupération du fichier :");
        System.out.println("Fichier à copier : "+file.toString());
    }
    
    
    public void upload(File sourceFile, String destURL) throws IOException { }
    
    
    /**
     * Enables to upload a file. Only this method id used to copy a local file
     * @throws IOException 
     */
    public void upload() throws IOException {
        
        download();
        
        urlDestination = completeUrl(urlDestination);
        System.out.println("Copie du fichier vers le répertoire : "+urlDestination);
        File destFile = new File(urlDestination.toString()+file.getName());
        
        if(!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(file).getChannel();
            destination = new FileOutputStream(destFile).getChannel();

            downloaded = 0;
            size = source.size();
            System.out.println("Taille du fichier à transférer : "+size+ " octets");
            /*************************** Boucle à revoir pour la progressBar ************************************/
            while((downloaded += destination.transferFrom(source, downloaded, size-downloaded))<size);
            System.out.println(getProgress());
            System.out.println(downloaded);
        }
        finally {
            if(source != null) {
                source.close();
            }
            if(destination != null) {
                destination.close();
            }
            System.out.println("Copie du fichier terminée");
        }
    }
  
    
}
